package v1

import (
	"app/api/v1/response"
	"app/internal/app/middleware"
	"app/internal/app/model"
	"app/internal/pkg/config"
	"app/internal/pkg/ecode"

	"github.com/gin-gonic/gin"
)

type loginRequest struct {
	Account  uint   `form:"account" json:"account" binding:"required"`
	Password string `form:"password" json:"password" binding:"required"`
}

func Login(ctx *gin.Context) {
	var request loginRequest
	err := ctx.ShouldBind(&request)
	if err != nil {
		response.Fail(ctx, err)
		return
	}

	user, err := model.GetUserByAccount(request.Account)
	if err != nil {
		response.Fail(ctx, err)
		return
	}

	if user.Password == request.Password {
		token, err := middleware.JWT.GenerateToken(user.ID, user.Account, user.Name)
		if err != nil {
			response.Error(ctx, err)
			return
		}
		ctx.SetCookie("token", token, int(config.JwtExpire.Seconds()), "/", config.Domain, config.Https, true)
		response.Success(ctx, "登录成功", ToUserVO(user))
	} else {
		response.Fail(ctx, ecode.ERROR_PASSWORD_WRONG)
	}
}
